package com.tanhua.dubbo.server.api;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.config.HuanXinConfig;
import com.tanhua.dubbo.server.enums.HuanXinMessageType;
import com.tanhua.dubbo.server.mapper.HuanXinUserMapper;
import com.tanhua.dubbo.server.pojo.HuanXinUser;
import com.tanhua.dubbo.server.service.RequestService;
import com.tanhua.dubbo.server.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.Date;

/**
 * 与环信平台集成的相关操作
 */
@Service(version = "1.0.0")
@Slf4j
public class HuanXinApiImpl implements HuanXinApi {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private HuanXinConfig huanXinConfig;
    @Autowired
    private RequestService requestService;
    @Autowired
    private HuanXinUserMapper huanXinUserMapper;

    /**
     * 获取环信token（获取管理员权限）
     *
     * @return token
     */
    @Override
    public String getToken() {
        return this.tokenService.getToken();
    }


    /**
     * 注册环信⽤户
     *
     * @param userId ⽤户id
     * @return 注册成功与否
     */
    @Override
    public Boolean register(Long userId) {
        String targetUrl = this.huanXinConfig.getUrl() +
                this.huanXinConfig.getOrgName() + "/" +
                this.huanXinConfig.getAppName() + "/users";

        HuanXinUser huanXinUser = new HuanXinUser();
        huanXinUser.setUsername("HX_" + userId); // 环信id
        huanXinUser.setPassword(IdUtil.simpleUUID()); // 随机生成登录密码

        HttpResponse response = this.requestService.execute(targetUrl,
                JSONUtil.toJsonStr(Arrays.asList(huanXinUser)), Method.POST);
        if (response.isOk()) {
            // 将环信的账号信息保存到数据库
            huanXinUser.setUserId(userId); // 用户id
            huanXinUser.setCreated(new Date()); // 创建时间
            huanXinUser.setUpdated(huanXinUser.getCreated()); // 更新时间

            this.huanXinUserMapper.insert(huanXinUser);

            return true;
        }

        return false;
    }


    /**
     * 根据⽤户Id查询环信账户信息
     *
     * @param userId ⽤户id
     * @return 环信用户对象
     */
    @Override
    public HuanXinUser queryHuanXinUser(Long userId) {
        QueryWrapper<HuanXinUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return this.huanXinUserMapper.selectOne(queryWrapper);
    }


    /**
     * 根据环信用户名查询用户信息
     *
     * @param userName 环信id
     * @return 环信用户对象
     */
    @Override
    public HuanXinUser queryUserByUserName(String userName) {
        QueryWrapper<HuanXinUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userName);
        return this.huanXinUserMapper.selectOne(queryWrapper);
    }

    /**
     * 添加好友关系（双向添加）
     *
     * @param userId   ⾃⼰的id
     * @param friendId 好友的id
     * @return 成功与否
     */
    @Override
    public Boolean addUserFriend(Long userId, Long friendId) {
        String targetUrl = this.huanXinConfig.getUrl() +
                this.huanXinConfig.getOrgName() + "/" +
                this.huanXinConfig.getAppName() + "/users/HX_" +
                userId + "/contacts/users/HX_" + friendId;

        try {
            // 404 -> 对⽅未在环信注册
            return this.requestService.execute(targetUrl, null, Method.POST).isOk();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }


    /**
     * 删除好友关系（双向删除）
     *
     * @param userId   ⾃⼰的id
     * @param friendId 好友的id
     * @return 成功与否
     */
    @Override
    public Boolean removeUserFriend(Long userId, Long friendId) {
        String targetUrl = this.huanXinConfig.getUrl() +
                this.huanXinConfig.getOrgName() + "/" +
                this.huanXinConfig.getAppName() + "/users/HX_" +
                userId + "/contacts/users/HX_" + friendId;

        try {
            // 404 -> 对⽅未在环信注册
            return this.requestService.execute(targetUrl, null, Method.DELETE).isOk();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 以管理员身份发送消息
     *
     * @param targetUserName     发送⽬标的⽤户名
     * @param huanXinMessageType 消息类型
     * @param msg                消息
     * @return
     */
    @Override
    public Boolean sendMsgFromAdmin(String targetUserName, HuanXinMessageType huanXinMessageType, String msg) {
        try {
            /* 一、请求路径 */
            String targetUrl = this.huanXinConfig.getUrl() +
                    this.huanXinConfig.getOrgName() + "/" +
                    this.huanXinConfig.getAppName() + "/messages";

            /* 二、请求体 */
            //{"target_type": "users","target": ["user2","user3"],"msg":{"type": "txt","msg": "testmessage"},"from": "user1"}
            String body = JSONUtil.createObj()
                    .set("target_type", "users")
                    .set("target", JSONUtil.createArray()
                            .set(targetUserName))
                    .set("msg", JSONUtil.createObj()
                            .set("type", huanXinMessageType.getType())
                            .set("msg", msg)).toString();
            //表示消息发送者;⽆此字段Server会默认设置为“from”:“admin”，有from字段但值为空串("") 时请求失败
            // .set("from", "")

            /* 三、发送请求 */
            return this.requestService.execute(targetUrl, body, Method.POST).isOk();
        } catch (JSONException e) {
            log.error("发送消息失败~ targetUserName = " + targetUserName+", type = " + huanXinMessageType.getType()+", msg = " + msg, e);
        }

        return false;
    }
}
